#include <WiFi.h>
#include <Update.h>
#include <HTTPClient.h>
//自定义模块
#include "OledModule/Oled.h"
#include "MqttModule/MyMqtt.h"

void performOTAUpdate(String binUrl) {

  WiFiClient client;
  HTTPClient http;

  http.begin(client, binUrl);
  int httpCode = http.GET();

  if (httpCode == HTTP_CODE_OK) {
    int contentLength = http.getSize();
    bool canBegin = Update.begin(contentLength);

    if (canBegin) {
      showMqStatus = true;
      u8g2.clearBuffer();
      showTxt(0, 30, "Begin OTA...");

      Serial.println("Begin OTA. This may take some time...");
      size_t written = Update.writeStream(http.getStream());

      if (written == contentLength) {
        Serial.println("Written : " + String(written) + " successfully");
      } else {
        Serial.println("Written only : " + String(written) + "/" + String(contentLength) + ". Retry?");
      }

      if (Update.end()) {
        Serial.println("OTA done!");
        u8g2.clearBuffer();
        showTxt(0, 30, "OTA done!");
        delay(500);
        if (Update.isFinished()) {
          Serial.println("Update successfully completed. Rebooting.");
          u8g2.clearBuffer();
          showTxt(0, 30, "Rebooting...");
          delay(1500);
          showMqStatus = false;
          u8g2.clearBuffer();

          ESP.restart();
        } else {
          Serial.println("Update not finished? Something went wrong!");
          showTxt(0, 30, "sys err!");
        }
      } else {
        Serial.println("Error Occurred. Error #: " + String(Update.getError()));
        showTxt(0, 30, "unknow err!");
      }
    } else {
      Serial.println("Not enough space to begin OTA");
      showTxt(0, 30, "space err!");
    }
  } else {
    Serial.println("Cannot download firmware. HTTP error: " + String(httpCode));
    showTxt(0, 30, "download err!");
  }

  http.end();
}
